/*********测试多线程同时申请释放***********/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/kthread.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/sched.h>
#include "hisi_l0_mem_pool.h"

#define THREAD_NUM 3 // 线程数量
#define TEST_LOOPS 10 // 每个线程测试次数
#define MEM_SIZE 8192 // 每次分配的内存大小

static struct task_struct *threads[THREAD_NUM];
static int thread_ids[THREAD_NUM];
static atomic_t mem_counter = ATOMIC_INIT(0);

// 线程工作函数
static int memory_test_thread(void *data)
{
	int id = *(int *)data;
	int i;
	void *pool_handle;
	void *ptr;

	for (i = 0; i < TEST_LOOPS; ++i) {
		pool_handle = NULL;
		ptr = l0_kmalloc(MEM_SIZE, 0);
		if (!ptr) {
			printk(KERN_ERR
			       "Thread %d: kmalloc failed at iteration %d\n",
			       id, i);
			continue;
		}

		// 原子操作计数
		atomic_inc(&mem_counter);

		// 模拟内存使用（这里可以添加内存操作）
		memset(ptr, 0xAA, MEM_SIZE);

		// 随机延时（模拟真实负载）
		usleep_range(100, 500);

		l0_kfree(ptr);
		atomic_dec(&mem_counter);

		// 添加调度点
		cond_resched();
	}

	printk(KERN_INFO "Thread %d completed\n", id);
	return 0;
}

// 模块初始化
static int __init test_l0_mem_pool_mul_init(void)
{
	int i;

	printk(KERN_INFO "Memory test module loaded\n");

	for (i = 0; i < THREAD_NUM; ++i) {
		thread_ids[i] = i;
		threads[i] = kthread_run(memory_test_thread, &thread_ids[i],
					 "kmem_test/%d", i);
		if (IS_ERR(threads[i])) {
			printk(KERN_ERR "Failed to create thread %d\n", i);
			return PTR_ERR(threads[i]);
		}
	}

	return 0;
}

// 模块退出
static void __exit test_l0_mem_pool_mul_exit(void)
{
	// 检查内存泄漏
	if (atomic_read(&mem_counter) != 0) {
		printk(KERN_ALERT
		       "WARNING: Memory leak detected! Counter: %d\n",
		       atomic_read(&mem_counter));
	}

	printk(KERN_INFO "Memory test module unloaded\n");
}

module_init(test_l0_mem_pool_mul_init);
module_exit(test_l0_mem_pool_mul_exit);

MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("Multi-threaded memory allocation test module");
